package com.stormrage.edu.ctrl.student;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.stormrage.constants.ErrCons;
import com.stormrage.edu.serv.student.StuAcctServ;
import com.stormrage.edu.serv.student.StuInfoServ;
import com.stormrage.entity.adm.req.PassReq;
import com.stormrage.entity.rep.ErrorRep;
import com.stormrage.entity.student.StuAcct;
import com.stormrage.entity.student.StuInfo;
import com.stormrage.entity.student.req.AvatarReq;
import com.stormrage.entity.student.req.StuAcctReq;
import com.stormragetech.core.ctrl.BaseCtrl;
import com.stormragetech.core.exception.StormrageTechException;

/**
 * @author www.stormragetech.com
 * @date 2016年1月19日
 * @version 1.0.0
 */
@Controller
@RequestMapping("/user")
public class StuAcctCtrl extends BaseCtrl {

	private static final Logger logger = LoggerFactory.getLogger(StuAcctCtrl.class);

	@Value("#{constants['html.title']}")
	private String htmlTitle;

	@Value("#{constants['html.logo']}")
	private String htmlLogo;

	@Value("#{constants['path.root']}")
	private String rootPath;

	@Value("#{constants['url.root']}")
	private String rootUrl;

	@Value("#{constants['path.image']}")
	private String imagePath;

	@Autowired
	private StuAcctServ stuAcctServ;

	@Autowired
	private StuInfoServ stuInfoServ;

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String index(Model model) {

		logger.debug(" 【 Controller 】- 【 AcctCtrl 】- 【 index 】-【 GET 】-【 STARTED 】");

		try {

			// ------------------ 获取用户信息 ------------------
			Subject currentUser = SecurityUtils.getSubject();
			StuAcct curr = stuAcctServ.queryByAcct(currentUser.getPrincipal().toString());

			// ------------------ Model 赋值 ------------------
			model.addAttribute("htmltitle", htmlTitle);
			model.addAttribute("htmllogo", htmlLogo);
			model.addAttribute("ipath", rootUrl + imagePath);
			model.addAttribute("user", curr);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】- 【 AcctCtrl 】- 【 index 】-【 GET 】-【 COMPLETED 】");
		return "user/index";
	}

	@RequestMapping(value = "/registration", method = RequestMethod.GET)
	public String registration(Model model) {

		logger.debug(" 【 Controller 】- 【 AcctCtrl 】- 【 Registration 】-【 GET 】-【 STARTED 】");

		try {

			// ------------------ Model 赋值 ------------------
			model.addAttribute("htmltitle", htmlTitle);
			model.addAttribute("htmllogo", htmlLogo);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】- 【 AcctCtrl 】- 【 Registration 】-【 GET 】-【 COMPLETED 】");
		return "user/registration";
	}

	@RequestMapping(value = "/registration", method = RequestMethod.POST)
	public String registration(StuAcctReq req, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】- 【 AcctCtrl 】- 【 Registration 】-【 POST 】-【 STARTED 】");

		logger.debug(" 请求的参数req为 " + req.toString());

		ErrorRep err = null;
		String errMsg = "";

		try {

			stuAcctServ.create(req);

			errMsg = "注册成功，请登录";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = e.getMessage();
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/user/registration";
		}

		logger.debug(" 【 Controller 】- 【 AcctCtrl 】- 【 Registration 】-【 POST 】-【 COMPLETED 】");
		return "redirect:/result";
	}

	@RequestMapping(value = "/login")
	public String login(HttpServletRequest req, Model model) {

		logger.debug(" 【 Controller 】- 【 Acct 】- 【 Login 】-【 GET/POST 】- 开始运行  ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ 登录失败返回信息 ------------------
			String exceptionClassName = (String) req.getAttribute("shiroLoginFailure");
			// System.out.println();
			// String exception =
			if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
				errMsg = "用户名不存在";
				err = ErrorRep.instance(false, errMsg);
			} else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
				errMsg = "用户名/密码错误";
				err = ErrorRep.instance(false, errMsg);
			} else if (LockedAccountException.class.getName().equals(exceptionClassName)) {
				errMsg = "用户被锁定";
				err = ErrorRep.instance(false, errMsg);
			} else if (exceptionClassName != null) {
				errMsg = "其他错误";
				err = ErrorRep.instance(false, errMsg);
			}

			model.addAttribute("error", err);
			model.addAttribute("htmltitle", htmlTitle);
			model.addAttribute("htmllogo", htmlLogo);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}
		return "user/login";
	}

	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(Model model) {

		logger.debug(" 【 Controller 】- 【 AcctCtrl 】- 【 Edit 】-【 GET 】-【 STARTED 】");

		try {

			// ------------------ 获取用户信息 ------------------
			Subject currentUser = SecurityUtils.getSubject();
			StuAcct curr = stuAcctServ.queryByAcct(currentUser.getPrincipal().toString());

			// ------------------ 获取用户信息 ------------------
			StuInfo info = stuInfoServ.queryByAcct(curr.getId());
			if (null != info)
				model.addAttribute("data", info);

			// ------------------ Model 赋值 ------------------
			model.addAttribute("htmltitle", htmlTitle);
			model.addAttribute("htmllogo", htmlLogo);
			model.addAttribute("ipath", rootUrl + imagePath);
			model.addAttribute("user", curr);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】- 【 AcctCtrl 】- 【 Edit 】-【 GET 】-【 COMPLETED 】");
		return "user/edit";
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public String edit(StuInfo req, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】- 【 AcctCtrl 】- 【 Edit 】-【 POST 】-【 STARTED 】");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ 获取用户信息 ------------------
			Subject currentUser = SecurityUtils.getSubject();
			StuAcct curr = stuAcctServ.queryByAcct(currentUser.getPrincipal().toString());

			// ------------------ 修改密码 ------------------
			req.setAcctId(Integer.valueOf(curr.getId()));
			stuInfoServ.update(req);

			// ------------------ 赋值 Model ------------------
			errMsg = "修改资料成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "修改资料失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/user/edit";
		}

		logger.debug(" 【 Controller 】- 【 AcctCtrl 】- 【 Edit 】-【 POST 】-【 COMPLETED 】");
		return "redirect:/user/edit";

	}

	@RequestMapping(value = "/pass", method = RequestMethod.GET)
	public String pass(Model model) {

		logger.debug(" 【 Controller 】- 【 Acct 】- 【 EditPass 】-【 GET 】- 开始运行  ");

		try {

			// ------------------ 获取用户信息 ------------------
			Subject currentUser = SecurityUtils.getSubject();
			StuAcct curr = stuAcctServ.queryByAcct(currentUser.getPrincipal().toString());

			// ------------------ Model 赋值 ------------------
			model.addAttribute("htmltitle", htmlTitle);
			model.addAttribute("htmllogo", htmlLogo);
			model.addAttribute("ipath", rootUrl + imagePath);
			model.addAttribute("user", curr);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}
		return "user/pass";
	}

	@RequestMapping(value = "/pass", method = RequestMethod.POST)
	public String pass(PassReq req, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】- 【 Acct 】- 【 EditPass 】-【 POST 】- 开始运行  ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ 获取用户信息 ------------------
			Subject currentUser = SecurityUtils.getSubject();
			StuAcct curr = stuAcctServ.queryByAcct(currentUser.getPrincipal().toString());

			// ------------------ 修改密码 ------------------
			req.setAcct(curr.getAcct());
			stuAcctServ.updatePass(req);

			// ------------------ 赋值 Model ------------------
			errMsg = "修改密码成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "修改密码失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/user/pass";
		}

		return "redirect:/user/pass";

	}

	@RequestMapping(value = "/upload", method = RequestMethod.GET)
	public String upload(Model model) {

		logger.debug(" 【 Controller 】- 【 AcctCtrl 】- 【 Image 】-【 GET 】-【 STARTED 】");

		try {

			// ------------------ 获取用户信息 ------------------
			Subject currentUser = SecurityUtils.getSubject();
			StuAcct curr = stuAcctServ.queryByAcct(currentUser.getPrincipal().toString());

			// ------------------ Model 赋值 ------------------
			model.addAttribute("htmltitle", htmlTitle);
			model.addAttribute("htmllogo", htmlLogo);
			model.addAttribute("ipath", rootUrl + imagePath);
			model.addAttribute("user", curr);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】- 【 AcctCtrl 】- 【 Image 】-【 GET 】-【 COMPLETED 】");
		return "user/upload";
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String upload(@RequestParam(value = "file", required = false) MultipartFile file,
			RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】- 【 AcctCtrl 】- 【 Image 】-【 POST 】-【 STARTED 】");

		ErrorRep err = null;
		String errMsg = "";

		if (null == file) {

			StormrageTechException exception = StormrageTechException.instance(ErrCons.CTRL_ERR, "图片不能为空",
					StormrageTechException.ERR_APP, "【 AcctCtrl 】-【 Image 】");

			err = ErrorRep.instance(false, exception.getMessage());
			redirect.addFlashAttribute("err", err);

			return "redirect:/user/upload";

		}

		try {

			// ------------------ 获取用户信息 ------------------
			Subject currentUser = SecurityUtils.getSubject();
			StuAcct curr = stuAcctServ.queryByAcct(currentUser.getPrincipal().toString());

			// ------------------ 修改密码 ------------------
			AvatarReq req = AvatarReq.instance(curr.getId(), rootPath, file);
			stuAcctServ.updateAvatar(req);

			// ------------------ 赋值 Model ------------------
			errMsg = "上传照片成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "上传照片失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/user/upload";
		}

		logger.debug(" 【 Controller 】- 【 AcctCtrl 】- 【 Image 】-【 POST 】-【 COMPLETED 】");
		return "redirect:/user/upload";

	}

}
